package ocean.chinacraft.common.world.block.function.container;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IWorldPosCallable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;
import ocean.chinacraft.common.ModContainer;
import ocean.chinacraft.common.ModBlocks;
import ocean.chinacraft.common.ModItems;

import javax.annotation.Nonnull;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 养蚕架容器
 *
 * @author zhang
 * @since 2021/11/15
 */
public class SericultureFrameBlockContainer extends Container {

    private final TileEntity tileEntity;

    private final PlayerEntity playerEntity;

    private final IItemHandler playerInventory;

    public SericultureFrameBlockContainer(int containerId, World world, BlockPos pos, PlayerInventory playerInventory
            , PlayerEntity player) {
        super(ModContainer.SERICULTURE_FRAME_BLOCK_CONTAINER.get(), containerId);
        this.tileEntity = world.getBlockEntity(pos);
        this.playerEntity = player;
        this.playerInventory = new InvWrapper(playerInventory);
        layoutPlayerInventorySlots(9, 86);
        if (tileEntity != null) {
            tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h -> {
                addSlot(new SlotItemHandler(h, 0, 9, 23));
                addSlot(new SlotItemHandler(h, 1, 27, 23));
                addSlot(new SlotItemHandler(h, 2, 45, 23));
                addSlot(new SlotItemHandler(h, 3, 63, 23));
                addSlot(new SlotItemHandler(h, 4, 81, 23));
                addSlot(new SlotItemHandler(h, 5, 99, 23));
                addSlot(new SlotItemHandler(h, 6, 117, 23));
                addSlot(new SlotItemHandler(h, 7, 135, 23));
                addSlot(new SlotItemHandler(h, 8, 153, 23));
                addSlot(new SlotItemHandler(h, 9, 13, 50));
                addSlot(new SlotItemHandler(h, 10, 153, 50));
            });
        }
    }

    @Override
    public boolean stillValid(@Nonnull PlayerEntity player) {
        return Container.stillValid(IWorldPosCallable.create(tileEntity.getLevel(), tileEntity.getBlockPos()),
                player, ModBlocks.SERICULTURE_FRAME_BLOCK.get());
    }

    @Nonnull
    @Override
    public ItemStack quickMoveStack(@Nonnull PlayerEntity player, int index) {
        //TODO 可能添加shift快速移动功能
        return ItemStack.EMPTY;
    }

    private int addSlotRange(IItemHandler handler, int index, int x, int y, int amount, int dx) {
        for (int i = 0; i < amount; i++) {
            addSlot(new SlotItemHandler(handler, index, x, y));
            x += dx;
            index++;
        }
        return index;
    }

    private int addSlotBox(IItemHandler handler, int index, int x, int y, int horAmount, int dx, int verAmount,
                           int dy) {
        for (int j = 0; j < verAmount; j++) {
            index = addSlotRange(handler, index, x, y, horAmount, dx);
            y += dy;
        }

        return index;
    }

    private void layoutPlayerInventorySlots(int leftCol, int topRow) {
        addSlotBox(playerInventory, 9, leftCol, topRow, 9, 18, 3, 18);
        topRow += 58;
        addSlotRange(playerInventory, 0, leftCol, topRow, 9, 18);
    }

    /**
     * 动画渲染状态
     *
     * @return 0-> 正确. 1 -> 正确,但桑叶不足. 2 -> 错误,需要雨水保护. 3 -> 正确，但蚕茧已满.
     * 4 -> 错误,桑叶不足
     * 99 -> 拒绝
     */
    public int allow() {
        AtomicBoolean egg = new AtomicBoolean(false);
        AtomicBoolean leaf = new AtomicBoolean(false);
        AtomicBoolean other = new AtomicBoolean(false);
        AtomicBoolean silkwormCocoonsFull = new AtomicBoolean(false);
        LazyOptional<IItemHandler> capability =
                this.tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
        capability.ifPresent(res -> {
            silkwormCocoonsFull.set(!res.getStackInSlot(10).isEmpty() && res.getStackInSlot(10).getCount() >= 64);
            leaf.set(!res.getStackInSlot(9).isEmpty());
            for (int i = 0; i <= 8; i++) {
                if (!res.getStackInSlot(i).isEmpty()) {
                    //如果是一个卵
                    boolean hasEgg = res.getStackInSlot(i).getItem() == ModItems.SILKWORM_EGG.get();
                    if (hasEgg) {
                        egg.set(true);
                    } else {
                        other.set(true);
                    }
                }
            }
        });
        //是否有雨水保护
        World level = tileEntity.getLevel();
        if (level != null) {
            if (level.isRaining() && level.canSeeSky(tileEntity.getBlockPos())) {
                return 2;
            }
        }
        //有卵，但是没有其他
        if (egg.get() && !other.get()) {
            return 0;
        } else if (egg.get() && other.get()) {
            //包含了卵和其他的,蚕卵如果满了
            if (silkwormCocoonsFull.get()) {
                return 3;
            }
            //是否包含桑叶
            return leaf.get() ? 0 : 1;
        } else if (!egg.get() && other.get()) {
            if (silkwormCocoonsFull.get()) {
                return 3;
            }
            //没有卵，但是有其他
            return leaf.get() ? 0 : 4;
        }
        return 99;
    }

    public int addInformation() {
        return allow();
    }
}
